package com.heima.wemedia.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WmMaterialConstant;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadLocal.UserIdThreadLocal;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.IWmMaterialService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author chana
 * @since 2024-08-15
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {

    @Resource
    private WmMaterialMapper wmMaterialMapper;

    @Resource
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Resource
    private FileStorageService fileStorageService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {

        WmMaterial wmMaterial = null;
        try {
            wmMaterial = new WmMaterial();
            wmMaterial.setUrl(uploadFile(multipartFile));
            wmMaterial.setUserId(UserIdThreadLocal.getUserId());
            wmMaterial.setType(0);
            wmMaterial.setIsCollection(WmMaterialConstant.COLLECT_N_MATERIAL);
            wmMaterial.setCreatedTime(LocalDateTime.now());
        } catch (IOException e) {
            log.error("上传图片失败");
            return ResponseResult.errorResult(AppHttpCodeEnum.ERROR_UPDATA_FILE);
        }

        wmMaterialMapper.insert(wmMaterial);

        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 上传minio
     *
     * @param multipartFile
     * @return
     * @throws IOException
     */
    private String uploadFile(MultipartFile multipartFile) throws IOException {
        //2.
        String fileName = multipartFile.getOriginalFilename();
        //3.重复名可能性高
        String filePrefix = UUID.randomUUID().toString();

        //4.
        String file = fileName.substring(fileName.lastIndexOf(WmMaterialConstant.SPLIT_MULTIPARTFILE));

        //1.
        String url = fileStorageService.uploadHtmlFile(null, filePrefix+file, multipartFile.getInputStream());
        return url;
    }

    /**
     * 分页查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult pageList(WmMaterialDto dto) {
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmMaterial> wrapper = Wrappers.<WmMaterial>lambdaQuery()
                .eq(!StringUtils.isEmpty(dto.getIsCollection()), WmMaterial::getIsCollection, Integer.parseInt(dto.getIsCollection()))
                .orderByDesc(WmMaterial::getCreatedTime);

        page(page, wrapper);

        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());

        return result;
    }

    /**
     * 根据id修该收藏
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult updateCollect(Integer id) {
        //
        WmMaterial wmMaterial = getById(id);
        if (WmMaterialConstant.COLLECT_N_MATERIAL.equals(wmMaterial.getIsCollection())) {
            wmMaterial.setIsCollection(WmMaterialConstant.COLLECT_Y_MATERIAL);
        } else {
            wmMaterial.setIsCollection(WmMaterialConstant.COLLECT_N_MATERIAL);
        }

        wmMaterialMapper.updateById(wmMaterial);

        return ResponseResult.okResult(null);
    }

    /**
     * 删除素材
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public ResponseResult delPictureById(Integer id) {
        //1.删除minio中的素材
        WmMaterial wmMaterial = getById(id);
        fileStorageService.delete(wmMaterial.getUrl());
        //2.删除关系库
        LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.<WmNewsMaterial>lambdaQuery()
                .eq(WmNewsMaterial::getMaterialId, id);
        wmNewsMaterialMapper.delete(wrapper);
        //3.删除素材
        wmMaterialMapper.deleteById(id);

        return ResponseResult.okResult(null);
    }
}
